﻿#include "requestmapper.h"
#include <QDateTime>

#include "largefileuploadcontroller.h"

RequestMapper::RequestMapper(QObject *parent) : HttpRequestHandler(parent)
{
    m_requestMap.insert("largeFileUpload", new LargeFileUploadController(this));
}

RequestMapper::~RequestMapper()
{
    qDeleteAll(m_requestMap);
    m_requestMap.clear();
}

void RequestMapper::service(HttpRequest &request, HttpResponse &response)
{
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("P3P", "CP=CAO PSA OUR");
    if (!request.getHeader("Access-Control-Request-Method").isNull() && request.getMethod() == "OPTIONS")
    {
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,TRACE,OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,Origin,Accept");
        response.setHeader("Access-Control-Max-Age", 86400);
    }
    response.setHeader("Content-Type", "application/json;charset=utf-8");
    response.setHeader("Date", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss").toUtf8());
    QString path = request.getPath();
    QStringList pathList = path.split("/");
    // 因为path以 / 为开头，使用split，第一个元素为空串
    if (pathList.size() < 3 + 1)
    {
        this->returnError(response);
        return;
    }
    if (pathList.value(1) != "YanLei")
    {
        this->returnError(response);
        return;
    }

    //    HttpRequestHandler *handler = m_requestMap.value(pathList.value(2));
    if (m_requestMap.find(pathList.value(2)) != m_requestMap.end())
    {
        m_requestMap.value(pathList.value(2))->service(request, response);
    }
    else
    {
        this->returnError(response);
        return;
    }
}
